<?php


namespace app\admin\controller\merchant;


use app\admin\controller\com\Admin;
use app\common\controller\AppCommon;
use app\service\Page;
use think\Request;

class Index extends Admin
{
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        if (!bs_p('merchant')) {
            return $this->error('请先安装【多商户】应用');
        }
    }

    public function form()
    {
        if (!empty($this->param['id'])) {
            $this->assign('data', AppCommon::data_get('plugin_merchant', ['id' => intval($this->param['id'])]));
        }
        return $this->fetch();
    }

    //商家列表
    public function index()
    {
        $where = [];
        $status = isset($this->param['status']) && is_numeric($this->param['status']) ? intval($this->param['status']) : '';

        $keyword = !empty($this->param['keyword']) ? trim($this->param['keyword']) : '';
        $orderBy = 'id desc';
        $page = !empty($this->param['page']) ? intval($this->param['page']) : 1;
        $pageSize = 10;
        if (!empty($status)) {
            $where['status'] = 1;
        } elseif (is_numeric($status)) {
            $where['status'] = '0';
        }
        if (!empty($keyword)) {
            if (is_uid($keyword)) {
                $where['uid'] = $keyword;
            } else {
                $where['account'] = $keyword;
            }

        }
        $data = AppCommon::data_list('plugin_merchant', $where, $page . ',' . $pageSize, '*', $orderBy);

        $total = AppCommon::data_count('plugin_merchant', $where);

        if ($data) {
            $stores = AppCommon::data_list_nopage('stores', ['merchant_uid' => ['in', array_column($data, 'uid')]], 'store_name,store_num,merchant_uid');
            if ($stores) {
                $stores = array_column($stores, null, 'merchant_uid');
            }
            foreach ($data as &$v) {
                if (isset($stores[$v['uid']])) {
                    $v['store_name'] = $stores[$v['uid']]['store_name'];
                    $v['store_num'] = $stores[$v['uid']]['store_num'];
                } else {
                    $v['store_name'] = '暂未创建';
                    $v['store_num'] = '无';
                }
            }
            unset($v);
        }

        $this->assign('page', Page::set($data, $pageSize, $page, $total, $this->param, url()));
        $this->assign('data', $data);
        return $this->fetch();
    }

    //管理员操作
    public function action()
    {
        $id = !empty($this->param['id']) ? intval($this->param['id']) : 0;
        if (!empty($id)) {
            $data = AppCommon::data_get('plugin_merchant', ['id' => $id]);
            if (empty($data)) {
                data_return('账户不存在', -1);
            }
            //仅删除
            if (!empty($this->param['ac']) && $this->param['ac'] == 'del') {
                AppCommon::data_del('plugin_merchant', ['id' => $data['id']]);
                parent::add_admin_log(['title' => '删除商户', 'content' => $data]);
                data_return('删除成功');
            }
        }

        $rule = [
            ['type' => 'length', 'key' => 'user_name', 'rule' => '2,32', 'msg' => '昵称1~32字符',],
            ['type' => 'empty', 'key' => 'account', 'rule' => '1,16', 'msg' => '登录账号1~16字符',],
        ];
        $check = check_param($this->param, $rule);
        if ($check['code'] <> 0) {
            data_return($check['msg'], $check['code']);
        }

        //修改或者设置密码
        if (!empty($this->param['pwd1'])) {
            if (strlen($this->param['pwd1']) < 6) {
                data_return('密码不够安全', -1);
            }
            if ($this->param['pwd1'] !== $this->param['pwd2']) {
                data_return('两次密码不一样', -1);
            }
        }

        if (empty($data) && empty($this->param['pwd1'])) {
            data_return('请设置密码', -1);
        }
        $baseData = [
            'account' => trim($this->param['account']),
            'user_name' => trim($this->param['user_name']),
            'user_desc' => trim($this->param['desc']),
            'up_time' => time(),
            'status' => !empty($this->param['status']) ? intval($this->param['status']) : 0,
        ];
        //添加
        if (empty($data)) {
            $has = AppCommon::data_get('plugin_merchant', ['account' => trim($this->param['account'])], 'id');
            if (!empty($has['id'])) {
                data_return('登录账号已存在', -1);
            }
            $salt = get_random(10, false);
            $pwd = md5($this->param['pwd1'] . $salt);
            $uid = 'bs' . md5($this->param['account'] . rand(1, 999999) . time());
            while (true) {
                $tmp = AppCommon::data_get('plugin_merchant', ['uid' => $uid], 'id');
                if (empty($tmp['id'])) {
                    break;
                }
                $uid = 'bs' . md5($this->param['account'] . rand(1, 999999) . time() . get_random(10, false));
            }
            $baseData = array_merge($baseData, [
                'uid' => $uid,
                'pwd' => $pwd,
                'salt' => $salt,
                'add_time' => time(),
            ]);
            AppCommon::data_add('plugin_merchant', $baseData);
        } else {
            if (!empty($this->param['pwd1'])) {
                $salt = get_random(10, false);
                $pwd = md5($this->param['pwd1'] . $salt);
                $baseData = array_merge($baseData, [
                    'pwd' => $pwd,
                    'salt' => $salt,
                ]);
            }

            AppCommon::data_update('plugin_merchant', ['id' => $data['id']], $baseData);
        }

        parent::add_admin_log(['title' => '增改商户', 'content' => $baseData]);
        data_return('操作成功');
    }

    //店铺列表
    public function stores()
    {
        $where = [];
        $status = isset($this->param['status']) && is_numeric($this->param['status']) ? intval($this->param['status']) : '';
        $is_check = isset($this->param['is_check']) && is_numeric($this->param['is_check']) ? intval($this->param['is_check']) : '';

        $keyword = !empty($this->param['keyword']) ? trim($this->param['keyword']) : '';
        $page = !empty($this->param['page']) ? intval($this->param['page']) : 1;
        $pageSize = 10;
        if (!empty($status)) {
            $where['a.status'] = 1;
        } elseif (is_numeric($status)) {
            $where['a.status'] = '0';
        }
        if (is_numeric($is_check)) {
            $where['a.is_check'] = $is_check;
        }
        if (!empty($keyword)) {
            if (is_uid($keyword)) {
                $where['a.uid'] = $keyword;
            } else {
                $where['a.store_name|b.account|b.user_name'] = ['like', "%$keyword%"];
            }
        }
        $data = AppCommon::db('stores')
            ->alias('a')
            ->join('plugin_merchant b', 'a.merchant_uid=b.uid', 'left')
            ->where($where)
            ->field('a.id,a.store_name,a.store_num,a.add_time,a.up_time,a.store_logo,a.status,a.is_check,a.merchant_uid')
            ->field('b.user_name,b.account,b.status as userStatus')
            ->order('a.id desc')
            ->page($page . ',' . $pageSize)
            ->select();

        $total = AppCommon::db('stores')
            ->alias('a')
            ->join('plugin_merchant b', 'a.merchant_uid=b.uid', 'left')
            ->where($where)
            ->count();

        if ($data) {
            foreach ($data as &$v) {
                if (empty($v['merchant_uid'])) {
                    $v['user_name'] = '<span class="bs-red">平台</span>';
                    $v['account'] = '超级管理';
                }
            }
            unset($v);
        }

        $this->assign('page', Page::set($data, $pageSize, $page, $total, $this->param, url()));
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function login_log()
    {
        $where = [];
        $keyword = !empty($this->param['keyword']) ? trim($this->param['keyword']) : '';

        $page = !empty($this->param['page']) ? intval($this->param['page']) : 1;
        $pageSize = 10;
        if (!empty($keyword)) {
            $where['pmll.uid|pm.user_name|pm.account'] = ['like', '%' . $keyword . '%'];
        }
        $total = AppCommon::db('plugin_merchant_login_log')
            ->alias('pmll')
            ->join('plugin_merchant pm', 'pmll.uid=pm.uid', 'left')
            ->where($where)
            ->count();

        $data = AppCommon::db('plugin_merchant_login_log')
            ->alias('pmll')
            ->join('plugin_merchant pm', 'pmll.uid=pm.uid', 'left')
            ->where($where)
            ->field('pmll.add_time,pmll.uid,pmll.ip,pm.user_name,pm.account')
            ->page($page . ',' . $pageSize,)
            ->order('pmll.id desc')
            ->select();


        if ($total) {
            foreach ($data as &$v) {
                $v['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
            }
            unset($v);
        }


        $this->assign('page', Page::set($data, $pageSize, $page, $total, $this->param, url()));
        $this->assign('data', $data);

        return $this->fetch();
    }
}